﻿<%@ WebHandler Language="C#" Class="addRegCourseData" %>

using System;
using System.Web;
using System.Web.SessionState;
using DatabaseComponent;
using System.Collections.Generic;
using System.Linq;

public class addRegCourseData : IHttpHandler , IRequiresSessionState {
    HttpSessionState Session = null;
    HttpRequest Request = null;
    HttpResponse Response = null;
    
    public void ProcessRequest (HttpContext context) {

        Session = context.Session;
        Request = context.Request;
        Response = context.Response;


        start();
        
        
        
        
    }


    /// <summary>
    /// this function will getting data from request and save the tick to the database.
    /// </summary>
    protected void start()
    {
        try
        {
            long CoursesID = long.Parse(Request["CoursesID"]);

            string CurrentData = Request["CurrentData"];

            string ScoID = Request["ScoID"];
            
            

            Persons currentPersons = getCurrentPersons();

            if (currentPersons == null)
                throw new Exception();

            Courses objCourses = new Courses ();
            objCourses.ID = CoursesID;
            
            List<RegisteredCourses> lstRegistered = new List<RegisteredCourses>(from obj in currentPersons.lstRegisteredCourses where obj.objCourses.Equals(objCourses) select obj);

            if (lstRegistered.Count == 0)
                throw new Exception();



            List<CoursesScoes> lstScoID = new List<CoursesScoes>(from obj in lstRegistered[0].lstCoursesScoes where obj.ID.ToString() == ScoID select obj);


            if (lstScoID.Count == 0)
                throw new Exception();



            lstScoID[0].ScoData = CurrentData;




            if (lstScoID[0].CurrentFormatedData.Keys.Contains("cmi.core.score.raw"))
            {
                Dictionary<string, string> dlNew = lstScoID[0].CurrentFormatedData;
                try
                {

                    if (lstRegistered[0].objCourses.objCoursesDegree.Degree > 0)
                    {

                        if (double.Parse(dlNew["cmi.core.score.raw"]) >= lstRegistered[0].objCourses.objCoursesDegree.Degree)
                        {
                            dlNew["cmi.core.lesson_status"] = "completed";
                            lstScoID[0].CurrentFormatedData = dlNew;

                        }
                    }




                }
                catch
                {
                }

            }
            
            
            

            if (lstScoID[0].CurrentFormatedData.Keys.Contains("cmi.core.lesson_status"))
            {
                if (lstScoID[0].CurrentFormatedData["cmi.core.lesson_status"].Substring(0, 1).ToLower() == "c" || lstScoID[0].CurrentFormatedData["cmi.core.lesson_status"].ToLower() == "passed")
                    lstScoID[0].IsCompleted = true;
                else
                    lstScoID[0].IsCompleted = false;
            }


            if (lstRegistered[0].LastTickDate == null)
            {
                lstRegistered[0].LastTickDate = DateTime.Now.AddSeconds(-10);
                lstRegistered[0].TotalSpendTime = 0;
            }

            DateTime dtNewDate = DateTime.Now;

            TimeSpan ts = dtNewDate - lstRegistered[0].LastTickDate.Value;

            lstRegistered[0].LastTickDate = dtNewDate;

            if (ts.TotalSeconds >= 10)
            {
                lstRegistered[0].TotalSpendTime = lstRegistered[0].TotalSpendTime + 1;
            }
            else
            {
                lstRegistered[0].TotalSpendTime = lstRegistered[0].TotalSpendTime + (long)ts.TotalSeconds;
            }


            //if (lstScoID[0].CurrentFormatedData.Keys.Contains("cmi.core.session_time"))
            //{
            //    if (lstRegistered[0].TotalSpendTime <= 0)
            //        lstRegistered[0].TotalSpendTime = (long)(TimeSpan.Parse(lstScoID[0].CurrentFormatedData["cmi.core.session_time"]).TotalSeconds);
            //    else
            //        lstRegistered[0].TotalSpendTime = lstRegistered[0].TotalSpendTime + (long)(TimeSpan.Parse(lstScoID[0].CurrentFormatedData["cmi.core.session_time"]).TotalSeconds);

               

            //}  
            
            



            
            
            
            


            CoursesScoesDB objCoursesScoesDB = new CoursesScoesDB(ConnectionStrings.LMS);
            objCoursesScoesDB.Update(lstScoID[0]);


            List<CoursesScoes> lstScoes = lstRegistered[0].lstCoursesScoes;

            bool bIsCompleted = true;
            
            for (int i = 0; i < lstScoes.Count; i++)
            {
                if (!lstScoes[i].IsCompleted)
                {
                    bIsCompleted = false;
                    break;
                }
            }

            if (bIsCompleted)
            {
                if (lstRegistered[0].objCourses.lstQuestions.Count > 0)
                {
                    lstRegistered[0].CourseStatus = (long)CourseEnum.Waiting_exam;
                }
                else
                {
                    if (lstRegistered[0].CourseStatus != (long)CourseEnum.Completed)
                    {
                        lstRegistered[0].CourseStatus = (long)CourseEnum.Completed;


                        FinishedExamsDB objFinishedExamsDB = new FinishedExamsDB(ConnectionStrings.LMS);

                        FinishedExams objFininshed = new FinishedExams();
                        objFininshed.Degree = 100;
                        objFininshed.RegisteredCoursesID = lstRegistered[0].ID;
                        objFininshed.Answers = "";
                        objFininshed.CurrentDate = DateTime.Now;
                        objFininshed.ExamIDs = "";
                        objFinishedExamsDB.Insert(objFininshed);
                        GlobalVars.addLog(lstRegistered[0].ID, 4);
                        GlobalVars.sendLogMail(lstRegistered[0], currentPersons, 4);

                        //GlobalVars.refreshRegistered(lstRegistered[0]);
                    }
                    
                }


               
                
                
                
            }
            else
                lstRegistered[0].CourseStatus = (long)CourseEnum.Learning;
            
            
            
                
            
            

            RegisteredCoursesDB objRegisteredCourses = new RegisteredCoursesDB(ConnectionStrings.LMS);
            objRegisteredCourses.Update(lstRegistered[0]);

            Response.Write("true");
            
            
            
        }
        catch
        {
            Response.Write("false");
        }
    }


    /// <summary>
    /// this function will get the current session person.
    /// </summary>
    /// <returns>the person running the course (null for a hacker trying to see course)</returns>
    protected Persons getCurrentPersons()
    {
        HttpSessionState st = Session;
        if (st == null)
            return null;
        if (st["CurrentPerson"] == null)
        {
           
            return null;
        }
        Persons currentPerson = null;

        try
        {
            currentPerson = (Persons)st["CurrentPerson"];

            PersonsDB objPersonsDB = new PersonsDB(ConnectionStrings.LMS);
            List<Persons> lstPersons = objPersonsDB.getPersonsByGenID(currentPerson.GenID);

            if (lstPersons.Count == 0)
            {
                return null;

            }

            currentPerson = lstPersons[0];

        }
        catch
        {
            return null;
        }






        return currentPerson;
    }
    
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}